var API = {
	nodeList: "http://127.0.0.1:6011/elcs/api/v1/node/ext/nodeList",
	getAllUsersByUUIds: "http://127.0.0.1:6011/elcs/api/v1/user/ext/getAllUsersByUUIds",
	searchUsersByUsername: "http://127.0.0.1:6011/elcs/api/v1/user/ext/searchByUsername"
}

//定义全局变量：
var addTeamUsers_chooseUserData = {
	saveNodes: {},
	currentUsers: {},
	checkedUsers: {}
};

function sendRequest(apiUrl, method, data, successCallback, errorCallback) {
	/*获取节点数据*/
	$.ajax({
		url: apiUrl,
		method: method,
		data: JSON.stringify(data),
		async: true,
		contentType: "application/json",
		headers: {
			"x-access-token": Cookie.getCookie("token")
		},
		success: function(data) {
			if(successCallback) {
				successCallback(data);
			}
		},
		error: function() {
			if(errorCallback) {
				errorCallback();
			}

		}
	});
}

/***************************************树操作*****************************/

//页面初始化

var setting = {
	data: {
		key: {
			name: "node_name",
		},
		simpleData: {
			enable: true,
			idKey: "uuid",
			pIdKey: "parent_uuid",
			rootPId: null
		}
	},
	view: {
		dblClickExpand: dblClickExpand,
		showIcon: false,
		showTitle: false,
		txtSelectedEnable: true,
		selectedMulti: false
	},
	callback: {
		onCollapse: zTreeOnCollapse,
		beforeClick: zTreeBeforeClick,
		onClick: zTreeOnClick,
		onCheck: zTreeOnCheck
	},
	check: {
		enable: true,
		chkStyle: "checkbox",
		chkboxType: {
			"Y": "s",
			"N": "s"
		}
	}

};

//初始化
function choose_user_checkbox() {
	//获取节点生成树
	sendRequest("http://127.0.0.1:6011/elcs/api/v1/node/ext/nodeList", "get", {}, function(data) {
		if(data.code == 0) {
			data = data.data;
			for(var i = 0; i < data.length; i++) {
				if(data[i].parent_uuid == null || data[i].parent_uuid.trim() == "") {
					data[i].parent_uuid = "root";
				}
			}
			//设置根节点
			data.push({
				"uuid": "root",
				"parent_uuid": null,
				"node_name": "通讯录",
				"user_num": null,
				"is_my_org": null,
				"open": true,
				"nocheck": true
			});
			var treeObj = $.fn.zTree.init($("#nodeTree"), setting, data);

			//var MYNODE = Cookie.getCookie("mynode");
			//展开并记录属于自己的节点及其子节点
			var isMineNodes = [];
			for(var i = 0; i < data.length; i++) {
				if(data[i].is_mine > 0) {
					var node = treeObj.getNodeByParam("uuid", data[i].uuid, null);
					isMineNodes.push(node);
					treeObj.expandNode(node, true, true, true);
					var mynodes = treeObj.transformToArray(node);
					for(var j = 0; j < mynodes.length; j++) {
						var s = $("#" + mynodes[j].tId + " .name").css("text-decoration", "underline");
					}
				}
			}

			//默认显示某个节点的数据
			var minLevelNode = isMineNodes[0];
			for(var i = 0; i < isMineNodes.length; i++) {
				if(minLevelNode.level > isMineNodes[i].level) {
					minLevelNode = isMineNodes[i];
				}
			}

			//触发点击事件，显示对应节点数据
			$("#" + minLevelNode.tId + "_a .name").click();

		}
	});

	//关闭滚动条缓冲
	$(".cuc-tree-wrapper").mCustomScrollbar({
		axis: "yx",
		scrollInertia: 0,
		advanced: {
			updateOnContentResize: true
		}
	});
	
		$(".cuc-user-wrapper").mCustomScrollbar();
		$(".cuc-selected-user").mCustomScrollbar();
		
	
}

function dblClickExpand(treeId, treeNode) {
	//对根节点不能双击展开
	return treeNode.level > 0;
}

/*更新滚动条*/
function zTreeOnCollapse(event, treeId, treeNode) {
	//会发生跳动
	//	$(".tree-wrapper").mCustomScrollbar("destroy");
	//	$(".tree-wrapper").mCustomScrollbar();
};

/*使根节点不能被选中*/
function zTreeBeforeClick(treeId, treeNode, clickFlag) {
	return treeNode.level > 0;
};

/****************************************树形逻辑******************************/

function zTreeOnClick(event, treeId, treeNode) {
	var treeObj = $.fn.zTree.getZTreeObj("nodeTree");
	var selectedNodeUuid = treeObj.getSelectedNodes()[0].uuid;
	addTeamUsers_chooseUserData.currentUsers = {};

	$("#chooseUserModal .cuc-left-panel table tbody").children().remove();

	checkUsersOperation.getAllUsersByUUIds([selectedNodeUuid], function() {
		var userArrObj = addTeamUsers_chooseUserData.saveNodes[selectedNodeUuid];
		for(var key in userArrObj) {
			if(userArrObj.hasOwnProperty(key) === true) {

				//更新当前显示用户列表
				addTeamUsers_chooseUserData.currentUsers[userArrObj[key].id] = userArrObj[key];

				//判断当前用户的选中状态
				var isChecked = addTeamUsers_chooseUserData.checkedUsers[userArrObj[key].id];

				//拼凑
				var trObj = '<tr>\
				<td><input type="checkbox" data-userid=' + userArrObj[key].id + ' id="user-' + userArrObj[key].id + '" class="cuc-checkbox-old" ' + (isChecked ? 'checked' : '') + '><label class="cuc-checkbox-new" for="user-' + userArrObj[key].id + '"></label></td>\
				<td>' + userArrObj[key].user_name + '</td>\
				<td>' + userArrObj[key].title + '</td>\
				</tr>';
				$("#chooseUserModal .cuc-left-panel table tbody").append(trObj);
			}
		}
	});
};

/*选中时触发获取选中的节点*/

function zTreeOnCheck(event, treeId, treeNode) {
	var treeObj = $.fn.zTree.getZTreeObj("nodeTree");

	if(treeNode.checked) {

		var checkedNodes = treeObj.getChangeCheckedNodes();
		//设置oldCheck
		for(var i = 0; i < checkedNodes.length; i++) {
			checkedNodes[i].checkedOld = checkedNodes[i].checked;
		}

		var checkedNodeUuids = [];

		for(var i = 0; i < checkedNodes.length; i++) {
			checkedNodeUuids.push(checkedNodes[i].uuid);
		}

		checkUsersOperation.getAllUsersByUUIds(checkedNodeUuids, function() {
			for(var i = 0; i < checkedNodeUuids.length; i++) {
				var userArrObj = addTeamUsers_chooseUserData.saveNodes[checkedNodeUuids[i]];
				var userArr = [];
				for(var key in userArrObj) {
					if(userArrObj.hasOwnProperty(key) === true) {
						userArr.push(userArrObj[key]);
					}
				}
				checkUsersOperation.addUsers(userArr);
			}
		});
	} else {
		var unCheckedNodes = treeObj.getChangeCheckedNodes();
		//设置oldCheck
		for(var i = 0; i < unCheckedNodes.length; i++) {
			unCheckedNodes[i].checkedOld = unCheckedNodes[i].checked;
		}

		var unCheckedNodeUuids = [];

		for(var i = 0; i < unCheckedNodes.length; i++) {
			unCheckedNodeUuids.push(unCheckedNodes[i].uuid);
		}

		checkUsersOperation.getAllUsersByUUIds(unCheckedNodeUuids, function() {
			for(var i = 0; i < unCheckedNodeUuids.length; i++) {
				var userArrObj = addTeamUsers_chooseUserData.saveNodes[unCheckedNodeUuids[i]];
				var userArr = [];
				for(var key in userArrObj) {
					if(userArrObj.hasOwnProperty(key) === true) {
						userArr.push(userArrObj[key]);
					}
				}
				checkUsersOperation.removeUsers(userArr);
			}
		});
	}

};

/*************************点击用户Panel相关事件********************/

$(document).on('click', '#chooseUserModal .cuc-user-wrapper table thead input', function() {
	var userArr = [];
	for(var key in addTeamUsers_chooseUserData.currentUsers) {
		if(addTeamUsers_chooseUserData.currentUsers.hasOwnProperty(key) === true) {
			userArr.push(addTeamUsers_chooseUserData.currentUsers[key]);
		}
	}
	if($(this).prop("checked")) {
		checkUsersOperation.addUsers(userArr);
	} else {
		checkUsersOperation.removeUsers(userArr);
	}

});

$(document).on('click', '#chooseUserModal .cuc-user-wrapper table tbody input', function() {

	if($(this).prop("checked")) {
		var currentCheckedUser = addTeamUsers_chooseUserData.currentUsers[$(this).data('userid')];
		checkUsersOperation.addUsers([currentCheckedUser]);
	} else {
		var currentCheckedUser = addTeamUsers_chooseUserData.currentUsers[$(this).data('userid')];
		checkUsersOperation.removeUsers([currentCheckedUser]);
	}

});

/*************************取消选择用户事件********************/
$(document).on('click', '#chooseUserModal .cuc-selected-user table tbody i', function() {
	var user = addTeamUsers_chooseUserData.checkedUsers[$(this).data('userid')];
	checkUsersOperation.removeUsers([user]);

});

/*********************************选择处理***************************/

checkUsersOperation = {
	addUsers: function(users) {
		for(var i = 0; i < users.length; i++) {

			//处理右则显示
			var currentObjLen = $("#chooseUserModal .cuc-right-panel [data-userid=" + users[i].id + "]").length;

			//如果还没有,添加
			if(currentObjLen == 0) {
				var trObj = '<tr>\
									<td>' + users[i].user_name + '</td>\
									<td>' + users[i].title + '</td>\
									<td><i class="iconfont icon-cancel" data-userid=' + users[i].id + '></i></td>\
								</tr>'
				$("#chooseUserModal .cuc-right-panel table tbody").append(trObj);
			}

			//处理数据
			addTeamUsers_chooseUserData.checkedUsers[users[i].id] = users[i];

			//处理中间
			$("#chooseUserModal .cuc-user-wrapper input[data-userid=" + users[i].id + "]").prop("checked", "checked");

			//处理左边树
			var nodeUserCount = Object.getOwnPropertyNames(addTeamUsers_chooseUserData.saveNodes[users[i].node_uuid]).length;

			//计算当前选择的节点同父节点的数量
			var count = 0;
			for(var key in addTeamUsers_chooseUserData.checkedUsers) {
				//只遍历对象自身的属性，而不包含继承于原型链上的属性。  
				if(addTeamUsers_chooseUserData.checkedUsers.hasOwnProperty(key) === true) {
					if(addTeamUsers_chooseUserData.checkedUsers[key].node_uuid == users[i].node_uuid) {
						count++;
					}
				}
			}

			if(count == nodeUserCount) {
				var treeObj = $.fn.zTree.getZTreeObj("nodeTree");
				var node = treeObj.getNodeByParam("uuid", users[i].node_uuid);
				treeObj.checkNode(node, true, false);
				node.checkedOld = node.checked;
				//当前table也要打勾
				$('#chooseUserModal .cuc-user-wrapper table thead input').prop("checked", "checked");
			}

		}

		//更新个数
		var totalCount = Object.getOwnPropertyNames(addTeamUsers_chooseUserData.checkedUsers).length;
		$("#chooseUserModal .cuc-right-panel .cuc-user-count span").text(totalCount);

	},
	removeUsers: function(users) {
		//处理数据
		for(var i = 0; i < users.length; i++) {

			//处理显示
			var currentObjLen = $("#chooseUserModal .cuc-right-panel [data-userid=" + users[i].id + "]").length;
			$("#chooseUserModal .cuc-right-panel tr i[data-userid=" + users[i].id + "]").closest("tr").remove();

			//处理数据
			delete addTeamUsers_chooseUserData.checkedUsers[users[i].id];

			//处理中间
			$("#chooseUserModal .cuc-user-wrapper input[data-userid=" + users[i].id + "]").prop("checked", "");

			//处理左边树
			var treeObj = $.fn.zTree.getZTreeObj("nodeTree");

			var node = treeObj.getNodeByParam("uuid", users[i].node_uuid);

			treeObj.checkNode(node, false, false);
			node.checkedOld = node.checked;

			//当前table也要取消打勾
			$('#chooseUserModal .cuc-user-wrapper table thead input').prop("checked", "");

		}

		//更新个数
		var totalCount = Object.getOwnPropertyNames(addTeamUsers_chooseUserData.checkedUsers).length;
		$("#chooseUserModal .cuc-right-panel .cuc-user-count span").text(totalCount);
	},
	getAllUsersByUUIds: function(uuids, callback) {
		var notFetchUuids = [];
		for(var i = 0; i < uuids.length; i++) {
			if(!addTeamUsers_chooseUserData.saveNodes[uuids[i]]) {
				notFetchUuids.push(uuids[i]);
			}
		}

		var data = {
			uuids: notFetchUuids
		};
		if(notFetchUuids.length == 0) {
			callback(uuids);
		} else {
			sendRequest("http://127.0.0.1:6011/elcs/api/v1/user/ext/getAllUsersByUUIds", "post", data, function(result) {
				if(result.code == 0) {
					var users = result.data;

					for(var i = 0; i < notFetchUuids.length; i++) {
						//不管有没有获取用户数据,记录uuid,防止下次继续请求获取
						addTeamUsers_chooseUserData.saveNodes[notFetchUuids[i]] = {};
					}

					for(var i = 0; i < users.length; i++) {
						//缓存用户数据
						if(!addTeamUsers_chooseUserData.saveNodes[users[i].node_uuid]) {
							addTeamUsers_chooseUserData.saveNodes[users[i].node_uuid] = {};
						}
						addTeamUsers_chooseUserData.saveNodes[users[i].node_uuid][users[i].id] = users[i];
					}

					callback(uuids);
				}
			});
		}
	}
}

/***************************************智能搜索*********************************/
var setTimeoutId;
$("#chooseUserModal .cuc-left-panel .cuc-search input").keyup(function() {
	$("#chooseUserModal .cuc-search ul li").remove();
	$("#chooseUserModal .cuc-search .cuc-search-list-wrapper").hide();

	if($(this).val().length < 1) {
		return;
	}
	//延迟请求500ms
	clearTimeout(setTimeoutId);
	var url = "http://127.0.0.1:6011/elcs/api/v1/user/ext/searchByUsername" + '?keyword=' + $(this).val() + '&pageno=1&pagesize=10';
	setTimeoutId = setTimeout(function() {
		sendRequest(url, "get", undefined, function(result) {
			if(result.code == 0) {
				if(result.data.length == 0) {
					$("#chooseUserModal .cuc-search .cuc-search-list-wrapper").hide();
				} else {
					$("#chooseUserModal .cuc-search .cuc-search-list-wrapper").show();
				}
				for(var i = 0; i < result.data.length; i++) {
					var domString = '<li>\
							<a href="#" data-nodeuuid="' + result.data[i].node_uuid + '" data-userid="' + result.data[i].id + '">' + result.data[i].user_name + ' ' + result.data[i].title + ' ' + result.data[i].full_name + '</a>\
						</li>';
					$("#chooseUserModal .cuc-search ul").append(domString);
				}
			}
		});
	}, 500);

});

$(document).on("click", "#chooseUserModal .cuc-search ul a", function() {
	$("#chooseUserModal .cuc-search .cuc-search-list-wrapper").hide();
	var node_uuid = $(this).data('nodeuuid');
	var user_id = $(this).data('userid');
	var treeObj = $.fn.zTree.getZTreeObj("nodeTree");
	var node = treeObj.getNodeByParam("uuid", node_uuid);

	//展开对应节点
	var nodes = node.getPath();
	if(nodes.length > 2) {
		treeObj.expandNode(nodes[nodes.length - 2], true, false);
	}

	checkUsersOperation.getAllUsersByUUIds([node_uuid], function() {

		//触发点击事件，显示对应节点数据
		$("#" + node.tId + "_a .cuc-name").click();
		checkUsersOperation.addUsers([addTeamUsers_chooseUserData.saveNodes[node_uuid][user_id]]);

		//树形滚动到目标节点:
		$("#chooseUserModal .cuc-left-panel .cuc-tree-wrapper").mCustomScrollbar('scrollTo', "#" + node.tId + "_a .name");

	});
});

/*********************************暴露调用**************************/
function chooseUser(callback) {
	Modal.show("#chooseUserModal");


	$("#chooseUserModal .cuc-cancel").click(function() {
		Modal.hide("#chooseUserModal");
	});
}